package com.kvn.test.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.testng.Assert;

import com.kvn.test.util.PathUtil;

/**
 * 加载测试配置
 * @author wzy on 2017/8/8.
 */
public abstract class ConfigLoader {
    /**
     * 加载 _config/${CUR_ENV} 下所有的properties文件配置
     */
    public static void loadConfigs(){
        String relativeConfigPath = "_config".concat(File.separator).concat(ConfigContext.CUR_ENV);
        File dir = new File(PathUtil.getAbsoluteClassPath(relativeConfigPath));
        // 兼容 target/test-classes 里面的资源文件
        if(!dir.exists()){
            dir = new File(PathUtil.getAbsoluteTestClassPath(relativeConfigPath));
        }

        Assert.assertTrue(dir.exists(), "配置目录不存在：[" + relativeConfigPath + "]");
        File[] files = dir.listFiles();
        for(File f : files){
            if(f.isFile() && f.getName().endsWith(".properties")){
                try {
                    FileInputStream fis = new FileInputStream(f);
                    Properties props = new Properties();
                    props.load(fis);
                    ConfigContext.CONFIG_MAP.put(f.getName(), props);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        System.out.println("配置加载完成===>" + JSON.toJSONString(ConfigContext.CONFIG_MAP));
    }

    /**
     * 加载当前环境
     * @return
     */
	public static String loadEnviroment() {
		String CUR_ENV = null;
		String relativePath = "_config/enviroment.properties";
        File enviroment = new File(PathUtil.getAbsoluteClassPath(relativePath));
        if(!enviroment.exists()){
            enviroment = new File(PathUtil.getAbsoluteTestClassPath(relativePath));
        }
        if(!enviroment.exists()){
            throw new RuntimeException("环境配置[_config/enviroment.properties]加载失败");
        }
        Properties props = new Properties();
        try {
            props.load(new FileInputStream(enviroment));
            CUR_ENV = props.getProperty("env", "dev");
            System.out.println("##########当前环境：" + CUR_ENV + "##########");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("环境配置[_config/enviroment.properties]加载失败");
        }
        return CUR_ENV;
	}

}
